package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.entity.RedisData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * @projectName: hm-dianping
 * @package: com.hmdp.utils
 * @className: CacheClient
 * @author: Mocrash
 * @description: TODO
 * @date: 2024/9/2 16:56
 * @version: 1.0
 */

@Slf4j
@Component
public class CacheClient {
    private StringRedisTemplate strRedisTemplate;

    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    public CacheClient(StringRedisTemplate strRedisTemplate){
        this.strRedisTemplate = strRedisTemplate;
    }

    /*普通存储*/
    public void set(String key, Object value, Long time, TimeUnit unit){
        strRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    /*逻辑过期存储*/
    public void setWithLogicalExpire(String key, Object value, Long time, TimeUnit unit){
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
    }

    /**/
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type, Function<ID, R> dbFallback,
                                          Long time, TimeUnit unit){
        String key = keyPrefix + id;
        String json = strRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)){
            //存在，直接返回
            return BeanUtil.toBean(json, type);
        }
        //是否是空串
        if (json != null){
            return null;
        }
        //未命中，查数据库。
        R ret = dbFallback.apply(id);
        if (ret == null){
            this.set(key, "", time, unit);
            return null;
        }
        this.set(key, ret, time, unit);
        return ret;
    }

    public <R, ID> R queryWithLogicalExpire(String keyPrefix, ID id, Class<R> type, Function<ID, R> function,
                                            Long expireSecond){
        String key = keyPrefix + id;
        String json = strRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if (StrUtil.isBlank(json)){
            //存在，直接返回
            return null;
        }
        //命中，反序列化
        RedisData bean = JSONUtil.toBean(json, RedisData.class);
        R dataBean = BeanUtil.toBean(bean.getData(), type);
        if (bean.getExpireTime().isBefore(LocalDateTime.now()) && tryLock("lock:" + key)){
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    R ret = function.apply((id));
                    RedisData cache = new RedisData();
                    cache.setData(ret);
                    cache.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond));
                    strRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(cache));
                }finally {
                    unLock("lock:" + key);
                }
            });
        }
        return dataBean;
    }

    private boolean tryLock(String key) {
        Boolean aBoolean = strRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unLock(String key) {
        strRedisTemplate.delete(key);
    }
}
